package com.neighbor.neighborhooduser.controller;


import com.alibaba.fastjson.JSONObject;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArraySet;
public class NotificationWebSocketHandler extends TextWebSocketHandler {

    // 存储所有在线用户会话
    public static final ConcurrentHashMap<String, WebSocketSession> ONLINE_SESSIONS = new ConcurrentHashMap<>();

    // 存储用户ID与会话ID的映射
    public static final ConcurrentHashMap<Integer, String> USER_SESSION_ID_MAP = new ConcurrentHashMap<>();

    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception {
        // 从URL参数中获取用户ID
        String query = session.getUri().getQuery();
        if (query != null && query.contains("userId=")) {
            String userIdStr = query.split("userId=")[1];
            try {
                int userId = Integer.parseInt(userIdStr);
                ONLINE_SESSIONS.put(session.getId(), session);
                USER_SESSION_ID_MAP.put(userId, session.getId());
                System.out.println("用户[" + userId + "]已连接，当前在线人数: " + ONLINE_SESSIONS.size());
            } catch (NumberFormatException e) {
                System.err.println("无效的用户ID格式: " + userIdStr);
            }
        }
    }

    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {
        String payload = message.getPayload();
        System.out.println("收到客户端消息: " + payload);

        // 解析客户端消息
        JSONObject jsonObject = JSONObject.parseObject(payload);
        String type = jsonObject.getString("type");

        // 处理不同类型的消息
        if ("heartbeat".equals(type)) {
            // 心跳检测响应
            JSONObject response = new JSONObject();
            response.put("type", "heartbeat");
            response.put("message", "pong");
            session.sendMessage(new TextMessage(response.toJSONString()));
        }
    }

    @Override
    public void afterConnectionClosed(WebSocketSession session, org.springframework.web.socket.CloseStatus status) throws Exception {
        // 移除会话
        ONLINE_SESSIONS.remove(session.getId());

        // 从用户映射中移除
        USER_SESSION_ID_MAP.entrySet().removeIf(entry -> entry.getValue().equals(session.getId()));

        System.out.println("连接已关闭，当前在线人数: " + ONLINE_SESSIONS.size());
    }

    /**
     * 向指定用户发送消息
     */
    public static void sendMessageToUser(Integer userId, String message) {
        String sessionId = USER_SESSION_ID_MAP.get(userId);
        if (sessionId != null) {
            WebSocketSession session = ONLINE_SESSIONS.get(sessionId);
            if (session != null && session.isOpen()) {
                try {
                    session.sendMessage(new TextMessage(message));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    /**
     * 广播消息给所有用户
     */
    public static void broadcast(String message) {
        ONLINE_SESSIONS.values().forEach(session -> {
            if (session.isOpen()) {
                try {
                    session.sendMessage(new TextMessage(message));
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        });
    }
}
